package com.enjoychain.www.security.controller.basic;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import com.enjoychain.www.security.entity.BasicFile;
import com.enjoychain.www.security.service.IBasicFileService;
import org.springframework.web.bind.annotation.RestController;

import static com.enjoychain.www.security.constant.BusinessTaskType.convertFromId;
import static com.ruoyi.common.utils.file.FileUploadUtils.extractFilename;

/**
 * <p>
 * 基础文件信息表 前端控制器
 * </p>
 *
 * @author ddmonk
 * @since 2023-01-29
 */
@Api(tags = "基础文件信息表")
@RestController
@RequestMapping("/security/basicFile")
@Slf4j
public class BasicFileController {

    @Value("${url}")
    String url;
    @Autowired
    IBasicFileService service;

//    @PreAuthorize("@ss.hasPermi('security:basic-file:query')")
    @GetMapping(value = "{id}")
    @ApiOperation("获取基础文件信息表详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "id",paramType = "path", dataType = "String")
    })
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = BasicFile.class)
    })
    public AjaxResult getBasicFileInfo(@PathVariable(value = "id", required = false) String id)
    {
        return AjaxResult.success("get-basic_file",service.getById(id));
    }

//    @PreAuthorize("@ss.hasPermi('security:basic-file:import')")
    @ApiOperation("导入基础文件信息表")
    @Log(title = "基础文件信息表", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception{
        ExcelUtil<BasicFile> util = new ExcelUtil<BasicFile>(BasicFile.class);
        List<BasicFile> infos = util.importExcel(file.getInputStream());
        return service.saveOrUpdateBatch(infos)?AjaxResult.success("批量插入成功"):AjaxResult.error("批量插入失败");
    }


    @ApiOperation("基础文件信息表导出模板下载")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response){
        ExcelUtil<BasicFile> util = new ExcelUtil<BasicFile>(BasicFile.class);
        util.importTemplateExcel(response,"基础文件信息表");
    }

//    @PreAuthorize("@ss.hasPermi('security:basic-file:add')")
    @PostMapping(consumes = {"application/json"}, produces = {"application/json"})
    @ApiOperation("新增基础文件信息表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = BasicFile.class),
    })
    @Log(title = "基础文件信息表", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody BasicFile entity){
        return service.save(entity)? AjaxResult.success("add-basic_file",entity): AjaxResult.error("新增基础文件信息表失败");
    }


//    @PreAuthorize("@ss.hasPermi('security:basic-file:update')")
    @PutMapping(consumes = {"application/json"}, produces = {"application/json"})
    @ApiOperation("修改基础文件信息表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = BasicFile.class)
    })
    @Log(title = "基础文件信息表", businessType = BusinessType.UPDATE)
    public AjaxResult update(@RequestBody BasicFile corpBasicInfo){
        String operate = "update-basic_file";
        return service.updateById(corpBasicInfo)?AjaxResult.success(operate,service.getById(corpBasicInfo.getId())) : AjaxResult.error("修改客户基础信息失败");
    }



    @Log(title = "基础文件信息表", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('security:basic-file:export')")
    @PostMapping("/export")
    @ApiOperation("导出基础文件信息表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    public void export(HttpServletResponse response,@RequestParam(name = "corpId", required = false) String corpId){
        QueryWrapper<BasicFile> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(corpId)) {
            queryWrapper.eq("corp_id",corpId);
        }
        List<BasicFile> list = service.list(queryWrapper);
        ExcelUtil<BasicFile> util = new ExcelUtil<BasicFile>(BasicFile.class);
        util.exportExcel(response,list, "导出基础文件信息表");
    }

    @PostMapping(value = "/fileUpload")
    @Log(title = "基础文件信息表", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('security:basic-file:upload')")
    @ApiOperation("上传文件接口")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    public AjaxResult fileUpload(@RequestParam(value = "file") MultipartFile file,
                                 @RequestParam(value = "connectId") String connectId,
                                 @RequestParam(value = "busiType") int busiType) {
        if (file.isEmpty()) {
            log.error("file is empty");
        }
        String fileName = file.getOriginalFilename();
        String dest = RuoYiConfig.getUploadPath();
        String filePath;
        String urlPath;
        try {
            String result = FileUploadUtils.upload(dest,file,true);
            filePath = result.split("&&")[0];
            urlPath = result.split("&&")[1];
        } catch (IOException e) {
            log.error(e.getMessage());
            return AjaxResult.error("fileUpload", "上传文件失败");
        }
        BasicFile basicFile = new BasicFile()
                .setPath(filePath).setConnectId(connectId).setBusiType(convertFromId(busiType)).setName(fileName).setUrl(url + urlPath);
        service.save(basicFile);
        return AjaxResult.success(basicFile);
    }

    @PostMapping(value = "/batch/fileUpload")
    @Log(title = "基础文件信息表", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('security:basic-file:upload')")
    @ApiOperation("上传文件接口批量")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    public AjaxResult fileUploadBatch(@RequestParam(value = "files") MultipartFile[] files,
                                 @RequestParam(value = "connectId") String connectId,
                                 @RequestParam(value = "busiType") int busiType) {
        for (MultipartFile file: files){
            fileUpload(file,connectId,busiType);
        }
        return AjaxResult.success();
    }


    @DeleteMapping(value = "/batch/delete")
    @Log(title = "基础文件信息表", businessType = BusinessType.DELETE)
//    @PreAuthorize("@ss.hasPermi('security:basic-file:delete')")
    @ApiOperation("批量删除文件")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    public AjaxResult deleteBatch(@RequestParam(value = "connectId") String connectId,
                                 @RequestParam(value = "busiType") int busiType) {
            service.removeFileByConnectIdAndBusiType(convertFromId(busiType),connectId);

        return AjaxResult.success();
    }

    @DeleteMapping(value = "{id}")
    @Log(title = "基础文件信息表", businessType = BusinessType.DELETE)
//    @PreAuthorize("@ss.hasPermi('security:basic-file:delete')")
    @ApiOperation("删除文件接口")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    public AjaxResult delete(@PathVariable(value = "id") int id) {
        try {
            service.removeFileById(id);
        } catch (IOException e) {
            log.error("DELETE FILE ERROR:", e);
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }
}
